import { Component } from 'react';
import { Card, Popover, message } from 'antd';
import { FooterToolbar } from '@ant-design/pro-layout';
import ProForm from '@ant-design/pro-form';
import { EditableProTable } from '@ant-design/pro-table';

const columns = [
    // {
    //     title: '用户ID',
    //     dataIndex: 'user_id',
    //     key: 'user_id',
    //     valueType: 'textarea',
    //     tip: '是唯一的 key',
    //     source: [
    //         {value: '8', text: '隐藏'},
    //     ]
    // },
    {
        title: '用户昵称',
        dataIndex: 'user_name',
        key: "user_name",
        valueType: 'textarea',

    },
    {
        title: '用户账号',
        dataIndex: 'user_account',
        key: 'user_account',
        valueType: 'textarea',
    },
    {
        title: '用户密码',
        dataIndex: 'user_password',
        valueType: 'textarea',
        key: 'user_password'
    },
    {
        title: '用户生日',
        dataIndex: 'user_birthday',
        valueType: 'textarea',
        key: 'user_birthday'
    },
    {
        title: '操作',
        key: 'action',
        valueType: 'option',
        render: (_, record, index, action) => {
          return [
            <a
              key="eidit"
              onClick={() => {
                  console.log(record)
                action?.startEditable(record.user_id-1);
              }}
            >
              编辑
            </a>,
          ];
        },
      },
];

class Account extends Component {
    constructor(props) {
        super(props)
        this.state = {
            data: [],
            error: [],
            setError: []
        }
    }

    componentDidMount() {
        fetch('http://localhost:3000/get_all_user')
            .then((response) => response.json())
            .then((json) => {
                this.setState({ data: json.data });
            })
            .catch((error) => console.error(error))
            .finally(() => {
                this.setState({ isLoading: false });
            });
    }

    getErrorInfo = (errors) => {
        const errorCount = errors.filter((item) => item.errors.length > 0).length;
    
        if (!errors || errorCount === 0) {
            return null;
        }
    
        const scrollToField = (fieldKey) => {
            const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
    
            if (labelNode) {
                labelNode.scrollIntoView(true);
            }
        };
    
        const errorList = errors.map((err) => {
            if (!err || err.errors.length === 0) {
                return null;
            }
    
            const key = err.name[0];
            return (
                <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
                    <CloseCircleOutlined className={styles.errorIcon} />
                    <div className={styles.errorMessage}>{err.errors[0]}</div>
                    <div className={styles.errorField}>{fieldLabels[key]}</div>
                </li>
            );
        });
        return (
            <span className={styles.errorIcon}>
                <Popover
                    title="表单校验信息"
                    content={errorList}
                    overlayClassName={styles.errorPopover}
                    trigger="click"
                    getPopupContainer={(trigger) => {
                        if (trigger && trigger.parentNode) {
                            return trigger.parentNode;
                        }
    
                        return trigger;
                    }}
                >
                    <CloseCircleOutlined />
                </Popover>
                {errorCount}
            </span>
        );
    };

    onFinish = async (values) => {
        setError([]);
        try {
            await fakeSubmitForm(values);
            message.success('提交成功');
        } catch {
            // console.log
        }
    };
    
    onFinishFailed = (errorInfo) => {
        setError(errorInfo.errorFields);
    };

    change = (value) => {
        console.log(value)
        fetch("http://localhost:3000/update_user", {
            method: "POST",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(value)
        })
        .then((response) => response.json())
        .then((json) => {
            this.setState({ data: json.data });
            if (json.msg) {
                message.success("保存成功")
                
            }
        }).catch((err) => {
            console.log(err)
        })
    }

    render() {
        return (
            <ProForm
                layout="vertical"
                hideRequiredMark
                submitter={{
                    render: (props, dom) => {
                      return (
                        <FooterToolbar>
                          {this.getErrorInfo(this.state.error)}
                          {dom}
                        </FooterToolbar>
                      );
                    },
                  }}
                onFinish={this.onFinish}
                onFinishFailed={this.onFinishFailed}
            >
                <Card title="成员管理" bordered={false}>
                    <ProForm.Item name="members">
                        <EditableProTable
                            value={this.state.data}
                            onChange={this.change}
                            recordCreatorProps={{
                                record: () => {
                                      return {
                                        key: `0${Date.now()}`,
                                    };
                                },
                            }}
                            columns={columns}
                            rowKey= 'key'
                        />
                    </ProForm.Item>
                </Card>
            </ProForm >
        )
    }
}

export default Account